<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle, {width: '100%'})"
  >
    <el-form
      ref="dataForm"
      :model="pageData"
      v-bind="options"
      :validate-on-rule-change="false"
    >
      <vc-page-comp
        v-for="(child, index) in currNode.children"
        :key="index"
        :node="child"
      />
    </el-form>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, getCurrentInstance, inject, computed, nextTick } from 'vue';
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";

const props = defineProps({
  node: Object,
});
const dataForm = ref();
const pageData = inject("pageData");
const initializing = ref(true);
const currNode = ref(props.node);
new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const init = (styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  nextTick(() => initializing.value = false);
};

const options = computed(() => {
  const compStyle = currNode.value.currCompStyle || {};
  const options = {};
  visual.addIfNotNull(options, compStyle, 'inline');
  visual.addIfNotNull(options, compStyle, 'size');
  visual.addIfNotNull(options, compStyle, 'labelPosition');
  visual.addIfNotNull(options, compStyle, 'labelWidth');
  visual.addIfNotNull(options, compStyle, 'labelSuffix');
  visual.addIfNotNull(options, compStyle, 'disabled');
  visual.addIfNotNull(options, compStyle, 'hideRequiredAsterisk');
  visual.addIfNotNull(options, compStyle, 'requireAsteriskPosition');
  visual.addIfNotNull(options, compStyle, 'disabled');
  return options;
});

const validate = (callback) => {
  const promise = new Promise((resolve, reject) => {
    if (!dataForm.value) {
      resolve(true);
      return;
    }

    dataForm.value.validate(valid => {
      if (valid) {
        resolve(valid);
      } else {
        reject(valid);
      }
    }).catch(e => {
      reject(e);
    });
  });
  promise.then(valid => callback && callback(valid));
  return promise;
};

onBeforeMount(() => init());

defineExpose({ validate });
</script>